using System;
using System.Text;
using System.Configuration;
using System.Collections.Generic;

using log4net;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Documents;
using Lucene.Net.QueryParsers;
using Lucene.Net.Analysis.Standard;

namespace Grr.Models
{
	public static class Search
	{
		private static readonly ILog log = LogManager.GetLogger(typeof(Search));

		public static SearchResult Query(string query_str, int max, int start)
		{
			List<SearchMatch> matches = new List<SearchMatch>(max + 1);
			bool more_available = false;

			log.InfoFormat("Performing Search: '{0}'", query_str);

			IndexSearcher searcher = new IndexSearcher(ConfigurationManager.AppSettings ["IndexesDirectory"]);
			MultiFieldQueryParser parser = new MultiFieldQueryParser(new string[] { "name", "text" }, new StandardAnalyzer());
			Query query = parser.Parse(query_str);
			Hits hits = searcher.Search(query);

			more_available = hits.Length() > max;
			for (int i = 0; i < Math.Min(max, hits.Length()); i++)
			{
				Document doc = hits.Doc(i);
				SearchMatch match = new SearchMatch(doc.Get("name"), StringUtil.Ellipsis (doc.Get("text"), 80), Grurrah.UrlForGrurrah(doc.Get("name")), i);
				matches.Add(match);
			}
			searcher.Close();

			return new SearchResult(matches, more_available);
		}
	}
}

